import { ref } from 'vue'
import { defineStore } from 'pinia'
export const useHeritageStore = defineStore('counter', () => {

  // 数据库里的数据
  const heritageData = ref([])
  // 编辑卡片隐藏与显示
  const dialogVisible = ref(false)
  // 字段名
  const formData = ref({
    project_name: '',
    category: '',
    sub_category: '',
    description: '',
    origin: '',
    characteristics: '',
    representative_artists: '',
    representative_method: '',
    popular_regions: '',
    related_festivals: '',
    protection_level: '',
    protection_unit: '',
    related_documents: '',
    multimedia_resources: '',
    record_date: ''
  })
  // 数据库里数据总量
  const total = ref(0)
  // 当前页码
  const currentPage = ref(1)
  // 页面数据
  const content = ref([])

  // 获取数据
  const fetchHeritageData = async (apiUrl) => {
    try {
      const response = await fetch(apiUrl)
      if (!response.ok) {
        throw new Error('网络响应失败')
      }
      const data = await response.json()
      heritageData.value = data
      total.value = data.length
      updateContent()
    } catch (error) {
      console.error('获取数据失败：' + error.message)
    }
  }

  // 分页
  const updateContent = () => {
    const start = (currentPage.value - 1) * 7
    const end = start + 7
    content.value = heritageData.value.slice(start, end)
  }

  // 分页
  const handleCurrentChange = (val) => {
    currentPage.value = val
    updateContent()
  }

  // 编辑
  const handleEdit = (id) => {
    const row = heritageData.value.find(item => item.id === id)
    if (row) {
      Object.keys(formData.value).forEach(key => {
        formData.value[key] = row[key] || ''
      })
      formData.value.id = row.id
      dialogVisible.value = true
    }
  }

  // 编辑
  const handleAdd = () => {
    dialogVisible.value = true
    Object.keys(formData.value).forEach(key => {
      formData.value[key] = ''
    })
  }

  // 删除单个
  const handleDelete = async (apiUrl, id) => {
    try {
      const response = await fetch(`${apiUrl}/${id}`, {
        method: 'DELETE'
      })
      if (response.ok) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        await fetchHeritageData(apiUrl)
      } else {
        throw new Error('删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }

  // 提交
  const submitForm = async (apiUrl) => {
    try {
      let response
      if (formData.value.id) {
        response = await fetch(`${apiUrl}/${formData.value.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formData.value)
        })
      } else {
        response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formData.value)
        })
      }
      if (response.ok) {
        ElMessage({
          type: 'success',
          message: formData.value.id ? '更新成功' : '添加成功'
        })
        dialogVisible.value = false
        await fetchHeritageData(apiUrl)
      } else {
        throw new Error(formData.value.id ? '更新失败' : '添加失败')
      }
    } catch (error) {
      ElMessage.error(`${formData.value.id ? '更新' : '添加'}失败：${error.message}`)
    }
  }

  return {
    heritageData,
    dialogVisible,
    formData,
    total,
    currentPage,
    content,
    fetchHeritageData,
    updateContent,
    handleCurrentChange,
    handleEdit,
    handleAdd,
    handleDelete,
    submitForm
  }
})